package com.ywy.chat.handler.impl;

import cn.hutool.json.JSONUtil;
import com.ywy.chat.ChatConstants;
import com.ywy.chat.handler.filter.ExcludeMineChannelContextFilter;
import com.ywy.chat.handler.MsgHandler;
import com.ywy.chat.message.ChatInMessage;
import com.ywy.chat.message.ChatOutMessage;
import com.ywy.chat.service.ChatService;
import com.ywy.chat.vo.ChatMessage;
import com.ywy.chat.vo.ChatTo;
import com.ywy.chat.vo.ChatUser;
import com.ywy.utils.ApplicationUtil;
import lombok.extern.slf4j.Slf4j;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;

import java.util.Date;

/**
 * 聊天消息处理器
 *
 * @author ywy
 * @date 2021/12/31 14:21
 */
@Slf4j
public class ChatMsgHandler implements MsgHandler {
    @Override
    public void handler(String data, WsRequest wsRequest, ChannelContext channelContext) {
        ChatInMessage chatInMessage = JSONUtil.toBean(data, ChatInMessage.class);
        ChatUser mine = chatInMessage.getMine();
        ChatTo to = chatInMessage.getTo();

        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setContent(mine.getContent());
        chatMessage.setAvatar(mine.getAvatar());
        chatMessage.setMine(false);
        chatMessage.setUsername(mine.getUsername());
        chatMessage.setFromid(mine.getId());
        chatMessage.setId(ChatConstants.GROUP_ID);
        chatMessage.setTimestamp(new Date());
        chatMessage.setType(to.getType());

        ChatOutMessage chatOutMessage = new ChatOutMessage();
        chatOutMessage.setEmit(ChatConstants.MESS_TYPE_CHAT);
        chatOutMessage.setData(chatMessage);

        String responseData = JSONUtil.toJsonStr(chatOutMessage);
        log.info("ChatMsgHandler----->接收到群聊消息：{}", responseData);

        // 发送群聊消息
        WsResponse wsResponse = WsResponse.fromText(responseData, "utf-8");
        ExcludeMineChannelContextFilter filter = new ExcludeMineChannelContextFilter();
        filter.setCurrentContext(channelContext);
        // 群发信息
        Tio.sendToGroup(channelContext.getGroupContext(), ChatConstants.GROUP_NAME, wsResponse, filter);

        // 保存群聊消息
        ChatService chatService = (ChatService) ApplicationUtil.getBean("chatService");
        chatService.setGroupHistoryMsg(chatMessage);
    }
}
